import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {tableConfig, header} from '../data/config'
import {getUrlParam} from '../data/util'
import store from 'store'

const base = url.base,
  getOpenBuildingDetail = request.getOpenBuildingDetail;

let table,
  storeData,
  hobId = getUrlParam('id');

let resData = null
let searchData = {
  hbuList: [],
  htList: []
}

table = $('#table').bootstrapTable($.extend({}, tableConfig, {
  url: base + getOpenBuildingDetail,
  queryParams: function (params) {
    return $.extend({
      currentPage: params.pageNumber,
      pageSize: params.pageSize,
      hobId: hobId
    }, $('#searchForm').serializeObject())
  }, ajax: function (params) {  //  自定义ajax
    $.ajax({
      url: params.url,
      type: params.type,
      contentType: params.contentType,
      headers: {
        myToken: Cookies.get('myToken')
      },
      data: params.data
    })
      .done(function (res) {
        // console.log('res msg', res)
        resData = res.object.elements
        searchData.hbuList = res.hbuList
        searchData.htList = res.htList
        setSearchData(searchData)
        // console.log(searchData)
        setHeadInfo(res)
        params.success({
          total: res.object.totalRows,
          rows: res.object instanceof Array ? res.object : res.object.elements
        })

      })
  },
  columns: [
    {
      field: 'hbuNum',
      title: '楼栋',
      valign: 'middle'
    }, {
      field: 'floor',
      title: '楼层',
      valign: 'middle'
    }, {
      field: 'householdNo',
      title: '房号',
      valign: 'middle'
    }, {
      field: 'typeName',
      title: '户型描述',
      valign: 'middle',
      formatter: (v, r) => {
        return r.typeName + ' ' + r.htStructure + ' ' + '建面' + r.buildArea
      }
    }, {
      field: 'hosRebate',
      title: '折扣',
      valign: 'middle',
      formatter: (v, r) => {
        return r.hosRebate == 0 ? '-' : r.hosRebate
      }
    }, {
      field: 'totalPrice',
      title: '总价',
      valign: 'middle'

    }, {
      field: 'discounted',
      title: '折扣后总价',
      valign: 'middle',
      formatter: (v, r) => {
        return r.discounted > 0 ? r.discounted : r.totalPrice
      }
    }, {
      field: 'primaryNum',
      title: '预选总数',
      valign: 'middle'
    }, {
      field: 'planOne',
      title: '预选一',
      valign: 'middle'
    }, {
      field: 'planTwo',
      title: '预选二',
      valign: 'middle'
    }, {
      field: 'planThree',
      title: '预选三',
      valign: 'middle'
    }, {
      field: 'earnest',
      title: '定金金额',
      valign: 'middle',
      formatter: (v, r) => {
        // console.log('statsu:', r)

        return r.earnest / 100
      }
    }, {
      field: 'status',
      title: '状态',
      valign: 'middle',
      formatter: (v, r) => {
        // console.log('statsu:', r)
        let status
        switch (r.status) {
          case '0':
            status = '待售'
            break
          case '1':
            status = '在售'
            break
          case '2':
            status = '已锁'
            break
          case '3':
            status = '已售'
            break
          case '4':
            status = '成交'
            break
        }
        return status
      }
    }, {
      field: 'homeBuyer',
      title: '购房人',
      valign: 'middle'
    }, {
      field: 'status',
      valign: 'middle',
      align: 'center',
      width: '240px',
      title: '操作',
      formatter: (v, r) => {
        // console.log('r', r)
        switch (r.status) {
          case '0':
          case '1':
          case '2':
            return (
              `<div class="btn-group">
              <button type="button" data-id="${ r.id }" class="btn btn-default btn-detail">详情</button>                  
              <button type="button" data-id="${ r.id }" class="btn btn-default btn-stop" edit-shut-status="${r.shutStatus}">${r.shutStatus == '1' ? '停用' : '启用'}</button>                  
              <button type="button" data-id="${ r.id }" class="btn btn-default btn-modify">修改</button>                  
            </div>`
            )
            break
          case '3':
          case '4':
            return (
              `<div class="btn-group">
              <button type="button" data-id="${ r.id }" class="btn btn-default btn-detail">详情</button>                                   
            </div>`
            )
            break
        }
      }

    }
  ]
}))

// 点击列表的时候传递数据到全局变量
table.on('click-row.bs.table', (e, data, el) => {
  storeData = data
})

$('#search-btn').on('click', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage: 1,
    }, $('#searchForm').serializeObject())
  })
})

//验证输入的折扣是否符合规则
$(document).on('change', '#edit-discount', e => {
  e.preventDefault()
  let val = e.target.value
  if (val < 100 && val > 0) {
    e.target.value = Math.floor(val)
  } else if (!e.target.value) {

  }
  else {
    e.target.value = ''
    alert('请输入1-100之间的数字')
  }
})

//修改
$(document).on('click', '#table .btn-modify', (e) => {
  e.preventDefault();
  let id = $(e.target).attr('data-id')

  $.ajax({
    type: "POST",
    url: base + '/admin/house/getHouses.json\n',
    dataType: "json",
    data: {id: id},
    headers: {
      myToken: Cookies.get('myToken')
    },
  }).then((dog) => {
    // console.log('修改', dog.object.houses);
    resData.forEach(k => {
      if (k.id == id) {
        console.log('k===>>>', k)
        let obj = k
        let str = `<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                     <div class="modal-dialog modal-sm" role="document">
                       <div class="modal-content">
                         <div class="modal-header">
                           <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                           <h4 class="modal-title" id="myModalLabel">修改房源</h4>
                         </div>
                           <div class="modal-body">
                           <p><span class="span-title">楼盘：</span><span>${obj.buildName}</span></p>
                           <p> <span class="span-title">选择户型：</span><span>${obj.typeName}</span></p>
                           <p><span class="span-title">楼栋：</span><span>${obj.hbuNum}</span></p>
                           <p><span class="span-title">楼层：</span><span>${obj.floor}</span></p>
                           <p><span class="span-title">门牌号：</span><span>${obj.householdNo}</span></p>
                           <p><span class="span-title">门牌号：</span><span>${obj.htOrientation}</span></p>
                           <p><span class="span-title">价格类型:</span>
                           <span id="price-type" price-type="${obj.hPriceType}">${obj.hPriceType == 0 ? '建面' : '套内'}</span>
                           </p>
                           <p><span class="span-title" id="hello-hosUnitPrice" hosUnitPrice="${obj.hosUnitPrice}">单价：</span><input id="edit-price" type="text" value="${obj.hosUnitPrice}">元</p>
                           <p><span class="span-title">折扣：</span><input id="edit-discount" type="text" value="${obj.hosRebate == 0 ? '' : new Number(obj.hosRebate).toFixed(0)}">%</p>
                           <!--<p><span class="span-title">是否特价：</span><button class="btn btn-primary" edit-hIsSpecial="${dog.object.houses.hIsSpecial}" id="edit-hIsSpecial">${dog.object.houses.hIsSpecial === 0 ? '是' : '否'}</button></p>-->
                           <p class="special-price"><span class="span-title">是否特价：</span>
                                <input type="radio" id="price-yes" name="contact" value="是">
                                   <label for="price-yes">是</label>
                                 <input type="radio" id="price-no" name="contact" value="否">
                               <label for="price-no">否</label>
                           </p>
                           <p><span class="span-title">总价：</span><span>${obj.totalPrice}元</span></p>
                           <p><span class="span-title">折扣后总价：</span><span>${Math.floor(obj.discounted == 0 ? obj.totalPrice : obj.discounted)}元</span></p>
                           <button id="edit-id" edit-id="${obj.buildId}" type="button" class="btn btn-primary">提交</button>
                          </div>
                       </div>
                      </div>
                     </div>`
        $('#myModal').remove()
        $('.content-wrap').append(str)
        // $('#').
        if (dog.object.houses.hIsSpecial) {
          $('#price-yes').attr('checked', true)
        } else {
          $('#price-no').attr('checked', true)
        }

        $('#myModal').modal('show')

        // $('#edit-hIsSpecial').on('click', e => {
        //   let str = $(e.target).attr('edit-hisspecial')
        //   if (str == 1) {
        //     str = 0
        //   } else if (str == 0) {
        //     str = 1
        //   }
        //   $(e.target).text(str === 0 ? '否' : '是')
        //   $(e.target).attr('edit-hisspecial', str)
        //   // console.log('asdasd', $('#edit-hIsSpecial').attr('edit-hasSpecial'), $('#edit-hIsSpecial'))
        // })
        $('#edit-id').on('click', e => {
          let bargainprice;
          [...document.querySelectorAll('.special-price input')].forEach(k => {
            if (k.checked) {
              // console.log(k.id)
              switch (k.id) {
                case 'price-yes':
                  bargainprice = 1
                  break
                case 'price-no':
                  bargainprice = 0
                  break
              }
            }
          })
          // console.log($('#edit-hIsSpecial').attr('edit-hasSpecial'))
          let obj = {
            recordId: k.id,
            danjia: $('#edit-price')[0].value || $('#hello-hosUnitPrice').attr('hosUnitPrice'),
            zekou: $('#edit-discount')[0].value || 0,
            bargainprice: bargainprice,
            hPriceType: $('#price-type').attr('price-type')
          }
          // console.log('adasdasd', obj.bargainprice)
          $.ajax({
            type: "POST",
            url: base + '/admin/house/edit.json',
            dataType: "json",
            data: obj,
            headers: {
              myToken: Cookies.get('myToken')
            },
          }).then(() => {
            //更改成功后刷新页面
            window.location.reload()
          })
        })
      }
    })
    $('#myModal').modal('show')
  })

});

//详情页
$(document).on('click', '#table .btn-detail', (e) => {
  e.preventDefault();
  let id = $(e.target).attr('data-id')
  let ObjId

  resData.forEach(k => {
    if (k.id == id) {
      // console.log('status', k.status)
      let status
      switch (k.status) {
        case '0':
          status = '待售'
          break
        case '1':
        case '2':
          status = '在售'
          break
        case '3':
          status = '已售'
      }
      $('#modal-info #top-select').attr('data-id', k.id)
      $('#modal-info #edit-buildName').text(k.buildName)
      $('#modal-info #edit-typeName').text(k.typeName + ' ' + k.htStructure + ' 建面' + k.buildArea + '㎡')
      $('#modal-info #edit-householdNo').text(k.householdNo)
      $('#modal-info #edit-hTotalPrice').text(k.totalPrice)
      $('#modal-info #edit-hosRebate').text(`${k.hosRebate != 0 ? k.hosRebate + '%' : '无'}`)
      $('#modal-info #edit-total-price').text(`${k.hosRebate != 0 ? k.totalPrice * (k.hosRebate / 100) : k.totalPrice}`)
      $('#modal-info #edit-status').text(status)
      $('#modal-info').modal('show')
    }
  })

  ObjId = $('#modal-info #top-select').attr('data-id')
  $.ajax({
    type: "POST",
    url: base + 'admin/onBuilding/details.json',
    dataType: "json",
    data: {id: ObjId},
    headers: {
      myToken: Cookies.get('myToken')
    },
  }).then(res => {
    console.log('ressss:', res, 'ObjId', ObjId)
    if (res.object.length > 0) {
      res.object.forEach(k => {
          if (k.type == '1') {  //type为1是唯一订单，2是显示在预选1、2、3里边的
            let date = new Date(k.rawAddTime)
            $('#edit-realName').text(k.realName)
            $('#edit-identityId').text(k.identityId)
            $('#edit-tradeAmount').text(k.tradeAmount / 100 + '元')
            $('#edit-rawAddTime').text(date.toLocaleDateString() + date.toLocaleTimeString())
          }
        }
      )
    } else {
      $('#edit-realName').text(' ')
      $('#edit-identityId').text(' ')
      $('#edit-tradeAmount').text(' ')
      $('#edit-rawAddTime').text(' ')
    }
  })

  $('#top-select').on('click', 'a', e => {
    $(e.target).addClass('btn-primary').siblings().removeClass('btn-primary')
    if ($(e.target).text() === '详情') {
      $('#all-info').addClass('info-active')
      $('#select-info').removeClass('info-active')
    } else {
      let ObjId = $('#modal-info #top-select').attr('data-id')
      $.ajax({
        type: "POST",
        url: base + 'admin/onBuilding/details.json',
        dataType: "json",
        data: {id: ObjId},
        headers: {
          myToken: Cookies.get('myToken')
        },
      }).then(res => {
        $('#select-info-show tbody').children().remove()

        function renderOrderInfo(res, date) {
          let str = `<tr><td class="phone">${res.phone}</td>
                    <td class="realName">${res.realName}</td>
                    <td class="rawAddTime">${date.toLocaleDateString() + date.toLocaleTimeString()}</td></tr>`
          return str
        }

        if (res.object.length > 0) {
          res.object.forEach(k => {
              if ($(e.target).attr('data-id') == k.reserveOrder) {
                let date = new Date(k.rawAddTime)
                $('#select-info-show tbody').append(renderOrderInfo(k, date))
              } else {
              }
            }
          )
        }
      })

      $('#all-info').removeClass('info-active')
      $('#select-info').addClass('info-active')
    }
  })

});

//启动停用
$(document).on('click', '#table .btn-stop', (e) => {
  e.preventDefault();

  let onOff = $(e.target).attr('edit-shut-status')
  let id = $(e.target).attr('data-id')

  switch ($(e.target).text()) {
    case '启用':
      onOff = '1'
      break
    case '停用':
      onOff = '0'
      break
  }
  $.ajax({
    type: "POST",
    url: base + '/admin/onBuilding/onOff.json',
    dataType: "json",
    data: {
      id: id,
      onOff: onOff
    },
    headers: {
      myToken: Cookies.get('myToken')
    },
  }).then(() => {
    table.bootstrapTable('refresh', {
      query: $.extend({
        currentPage: 1,
      }, $('#searchForm').serializeObject())
    })
  })

  // let id               = $(e.target).attr('data-id');
  // window.location.href = `./openDetail.html?id=${id}`
});

$('#search-btn').on('click', (e) => {
  e.preventDefault();
  // console.log($('#searchForm').serializeObject())
  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage: 1,
    }, $('#searchForm').serializeObject())
  })
})

//设置顶部房间信息
function setHeadInfo(res) {
  // console.log('header', res.hobInfo)
  const resTime = res.hobInfo.hobSpecificTime
  if (resTime) {
    let time = new Date(resTime)
    $('#head-hobSpecificTime').html(time.toLocaleDateString() + `</br>` + time.toLocaleTimeString())
  }
  $('#head-hobSpecificTime').html('无')

  $('#head-buildingName').text(res.hobInfo.buildingName)
  $('#head-hobPeriod').text(res.hobInfo.hobPeriod)
  $('#head-status').text(res.hobInfo.status == 2 ? '未开盘' : '已开盘')
  $('#head-hobInfoSize').text(res.hobInfoSize)
  $('#head-houseRemainCount').text(res.houseRemainCount)
}

//设置搜索栏select
function setSearchData(res) {
  if ($('#buildSearch').children().length < 2) {
    res.hbuList.forEach(k => {
      // console.log(k)
      let str = `<option value="${k.idStr}">${k.hbuNum}</option>`
      $('#buildSearch').append(str)
    })
    res.htList.forEach(k => {
      console.log('htlist===>>>', k)
      let str = `<option value="${k}">${k}</option>`
      $('#houseTypeSearch').append(str)
    })
  }

}
